package com.stars.easyms.logger.support.logback.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.status.ErrorStatus;
import com.stars.easyms.logger.config.EasyMsLoggerHelper;
import com.stars.easyms.logger.support.EasyMsOverride;
import com.stars.easyms.logger.support.logback.handler.EasyMsLoggingEvent;
import com.stars.easyms.logger.support.logback.util.EasyMsAsynAppenderUtil;

import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>className: EasyMsFileAppender</p>
 * <p>description: 重写FileAppender类</p>
 *
 * @author guoguifang
 * @date 2019-08-20 15:24
 * @since 1.3.0
 */
public final class EasyMsFileAppender extends FileAppender<ILoggingEvent> implements LockProvider, EasyMsOverride {

    @Override
    protected void writeOut(ILoggingEvent event) throws IOException {
        if (EasyMsLoggerHelper.isLogAsynEnabled()) {
            EasyMsAsynAppenderUtil.writeOut((EasyMsLoggingEvent) event, this, this.encoder);
        } else {
            super.writeOut(event);
        }
    }

    @Override
    protected void subAppend(ILoggingEvent event) {
        if (isStarted()) {
            try {
                writeOut(event);
            } catch (IOException e) {
                this.started = false;
                addStatus(new ErrorStatus("IO failure in appender", this, e));
            }
        }
    }

    @Override
    public ReentrantLock getReentrantLock() {
        return lock;
    }

    @Override
    public String getName() {
        return "file";
    }
}